package com.wb.server.tcp.server.handler;

import com.wb.tcp.common.utils.Iec104Constant;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 
* @ClassName: Unpack104Util  
* @Description: Solve TCP unpacking and sticky packet problems
* @author cy
* @date 2022-07-07
 */
public class Unpack104Handler extends ByteToMessageDecoder {

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
        // records the index at the beginning of th data
        int beginReader;  
        int newDataLength = 0;
        while (true) {  
            // Gets the index at the beginning of the header
            beginReader = buffer.readerIndex();  
            // recording a flag to reset the pointer
            buffer.markReaderIndex();  
            // reads the start flag of the protocol .break
            if (buffer.readByte() == Iec104Constant.HEAD_DATA) {
            	// records current data is new data
            	//reads data length
            	byte newDataLengthByte = buffer.readByte();
                newDataLength = newDataLengthByte & 0xFF;
                break;
            }
            continue;
        }

        if (buffer.readableBytes() < newDataLength) {
            buffer.readerIndex(beginReader);
            return;
        }

        newDataLength = newDataLength +  2;
        //reset pointer
        buffer.readerIndex(beginReader);
        ByteBuf data = buffer.readBytes(newDataLength);
        out.add(data); 
	}

}
